package com.lbd.project.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lbd.base.controller.BaseController;
import com.lbd.commons.Result;
import com.lbd.commons.ResultState;
import com.lbd.project.bean.TargetInfo;
import com.lbd.project.controller.vo.TargetVo;
import com.lbd.project.service.TargetService;
import com.lbd.util.ZipUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

/**
 * Created by Yuanbo on 2016/9/29.
 */
@RestController
@RequestMapping("/target")
public class TargetController extends BaseController {
    //@Autowired
    TargetService targetService;


    /**
     * 贷前管理-审核列表
     *
     * @param page
     * @param rows
     * @param targetVo
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result list(int page, int rows, TargetVo targetVo) {
        return new Result(ResultState.SUCCESS, "查询成功", targetService.findByPageConditionJpql(page, rows, targetVo));
    }

    /**
     * 更新审核后的标的信息
     *
     * @param targetId    标的id
     * @param auditStatus 审核状态
     * @param suggestion  审核意见
     * @param mjStart     募集开始时间
     * @param rzqx        融资期限
     * @return 审核后的标的信息
     */
    @RequestMapping(value = "/saveAudit", method = RequestMethod.POST)
    public Result saveAudit(@RequestParam("id") String targetId, @RequestParam("auditStatus") String auditStatus,
                            @RequestParam("suggestion") String suggestion, @RequestParam("mjStart") String mjStart,
                            @RequestParam("rzqx") String rzqx) {
        if (StringUtils.isNotBlank(auditStatus)) {
            //更新审核后的标的信息
            TargetInfo targetInfo = targetService.updateAuditMsg(targetId, auditStatus, suggestion, mjStart, rzqx);
            //保存标的信息
            targetService.update(targetInfo);
            return SUCCESS;
        } else {
            return new Result(ResultState.FAIL, "审核失败,审核状态为空");
        }
    }

    /**
     * 贷中管理-满标待审项目列表
     *
     * @param page     页码
     * @param rows     行数
     * @param targetVo 标的信息
     * @return 满标项目列表
     */
    @RequestMapping(value = "/findFullScaleList", method = RequestMethod.GET)
    public Result fullScaleList(int page, int rows, TargetVo targetVo) {
        return new Result(ResultState.SUCCESS, "查询成功", targetService.findFullScaleList(page, rows, targetVo));
    }


    /**
     * 满标待审项目手动放款
     *
     * @param targetId 放款标的
     * @return
     */
    @RequestMapping(value = "/fullScaleLoan", method = RequestMethod.POST)
    public Result fullScaleLoan(String targetId) {
        try {
            targetService.fullScaleLoan(targetId);
        } catch (Exception e) {
            return new Result(ResultState.FAIL, "放款失败");
        }
        return new Result(ResultState.SUCCESS, "放款成功");
    }

    /**
     * 贷前中理-借款中的项目列表
     *
     * @param page     页码
     * @param rows     行数
     * @param targetVo 标的信息
     * @return 借款中的项目列表
     */
    @RequestMapping(value = "/findLoanList", method = RequestMethod.GET)
    public Result loanList(int page, int rows, TargetVo targetVo) {
        return new Result(ResultState.SUCCESS, "查询成功", targetService.findLoansList(page, rows, targetVo));
    }

    /**
     * 贷前中理-流标中的项目列表
     *
     * @param page     页码
     * @param rows     行数
     * @param targetVo 筛选条件
     * @return 流标中的项目列表
     */
    @RequestMapping(value = "/findBidderList", method = RequestMethod.GET)
    public Result bidderList(int page, int rows, TargetVo targetVo) {
        return new Result(ResultState.SUCCESS, "查询成功", targetService.findBidderList(page, rows, targetVo));
    }

    /**
     * 贷前管理-查询出要审核的数据
     *
     * @param targetId 标的id
     * @return 一条审核数据
     */
    @RequestMapping(value = "/findTargetById", method = RequestMethod.GET)
    public Result findTargetById(@RequestParam("id") String targetId) {
        if (StringUtils.isBlank(targetId)) {
            return new Result(ResultState.FAIL, "标的ID为空");
        }
        return new Result(ResultState.SUCCESS, "查询成功", targetService.findById(targetId));
    }


    /**
     * 贷前中理-某标的投资记录
     *
     * @param page     页码
     * @param rows     行数
     * @param targetId 标的id
     * @return 投资列表
     */
    @RequestMapping(value = "/loanInvest", method = RequestMethod.GET)
    public Result loanInvest(int page, int rows, @RequestParam("id") String targetId) {
        if (StringUtils.isBlank(targetId)) {
            return new Result(ResultState.FAIL, "标的ID为空");
        }
        Page<Map> investByTargetId = targetService.findInvestByTargetId(page, rows, targetId);
        if (null == investByTargetId) {
            return SUCCESS;
        } else {
            return new Result(ResultState.SUCCESS, "查询成功", investByTargetId);
        }
    }

    /**
     * 投资情况中的-某笔投资的总投资人数,总投资金额
     *
     * @param targetId 标的id
     * @return 投资总人数\总金额
     */
    @RequestMapping(value = "/totalInvest", method = RequestMethod.GET)
    public Result totalInvest(@RequestParam("targetId") String targetId) {
        if (StringUtils.isBlank(targetId)) {
            return new Result(ResultState.FAIL, "标的ID为空");
        }
        String totalInvest = targetService.totalInvest(targetId);
        if (null == totalInvest) {
            return SUCCESS;
        } else {
            return new Result(totalInvest);
        }
    }

    /**
     * 更新风控信息图片
     *
     * @param oType       文件类型
     * @param fileContent 文件保存路径
     * @param targetId    标的id
     * @return 更新风控信息图片
     */
    @RequestMapping(value = "/uploadPic", method = RequestMethod.POST)
    public Result uploadPic(@RequestParam("oType") String oType, @RequestParam("fileContent") String fileContent,
                            @RequestParam("uploadTargetId") String targetId) {
        if (StringUtils.isBlank(oType) || StringUtils.isBlank(fileContent) || StringUtils.isBlank(targetId)) {
            return FAIL;
        }
        //更新风控信息图片
        targetService.updateProPic(targetId, fileContent, oType);
        return new Result(ResultState.SUCCESS, "更新成功");
    }

    /**
     * 删除风控信息图片
     *
     * @param targetId    标的id
     * @param fileContent 文件保存路径
     */
    @RequestMapping(value = "/removePic", method = RequestMethod.GET)
    public Result removePic(@RequestParam("id") String targetId, @RequestParam("fileContent") String fileContent) {
        //删除风控信息图片
        targetService.removeProPic(targetId, fileContent);
        return SUCCESS;
    }

    @Value("${filepath}")
    private String BASE_PATH;

    @RequestMapping(value = "/download/attachment/package", method = RequestMethod.GET)
    public void removePic(@RequestParam("id") String targetId, HttpServletResponse response) throws Exception {
        TargetInfo targetInfo = targetService.findById(targetId);
        JSONArray proveArray = JSONObject.parseArray(JSONObject.toJavaObject(JSON.parseObject(targetInfo.getOtherContent()), TargetVo.class).getProves());
        List<String> files = new ArrayList<>();
        for (Object o : proveArray) {
            JSONObject obj = (JSONObject) o;
            files.add(BASE_PATH + File.separator + obj.get("filecontent"));
        }
        String[] strings = Arrays.copyOf(files.toArray(), files.size(), String[].class);
        response.setContentType("application/zip");
        response.addHeader("Content-Disposition", "attachment;filename=" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ".zip");
        ZipUtils.compress(response.getOutputStream(), strings);
    }

    /**
     * 更新标的信息
     *
     * @param targetVo 要更新的字段
     */
    @RequestMapping(value = "/updateTargetMsg", method = RequestMethod.POST)
    public Result updateTargetMsg(TargetVo targetVo) {
        if (null != targetVo) {
            targetService.updateTargetMsg(targetVo);
            return new Result(ResultState.SUCCESS, "更新成功");
        }
        return new Result(ResultState.FAIL, "更新失败");
    }
}